<template>
	<view>
		<view class="echarts" :id="option.id" :style="estyle" :prop="option" :change:prop="echarts.update"
			@click="echarts.onClick"></view>
	</view>
</template>
<script>
	export default {
		name: 'Echarts',
		props: {
			option: {
				type: Object,
				required: true
			},
			estyle: {
				type: String,
				required: false,
				default: ""
			}
		},
		created() {
			// 设置随机数id
			let t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
			let len = t.length
			let id = ''
			for (let i = 0; i < 32; i++) {
				id += t.charAt(Math.floor(Math.random() * len))
			}
			this.option.id = id
			this.option={
				title: [{
					show: true,
					text: '综合上机排行',
					subtext: '单位：台',
					subtextStyle: {
						color: '#ffffff',
						lineHeight: 10,
					},
					textStyle: {
						color: '#fff',
						fontSize: 12
					},
					right: 140,
					top: '182%'
				}],
				grid: {
					right: 10,
					top: '192%',
					left: '30%',
					height: '100%'
				},
				length: {
					height: '100%'
				},
				xAxis: {
					show: false
				},
				yAxis: {
					top: '120%',
					type: 'category',
					inverse: true,
					nameGap: 10,
					axisLine: {
						show: false,
						lineStyle: {
							color: '#ddd'
						}
					},
					axisTick: {
						show: false,
						lineStyle: {
							color: '#ddd'
						}
					},
					axisLabel: {
						interval: 0,
						margin: 85,
						textStyle: {
							color: '#fff',
							align: 'left',
							fontSize: 12
						},
						rich: {
							a: {
								color: '#fff',
								backgroundColor: '#f0515e',
								width: 12,
								height: 12,
								align: 'center',
								borderRadius: 2
							},
							b: {
								color: '#fff',
								backgroundColor: '#24a5cd',
								width: 12,
								height: 12,
								align: 'center',
								borderRadius: 1
							}
						},
						formatter: function(params) {
							if (parseInt(params.slice(0, 2)) < 3) {
								return [
									'{a|' + (parseInt(params.slice(0, 2)) + 1) + '}' + '  ' + params
									.slice(2)
								].join('\n')
							} else {
								return [
									'{b|' + (parseInt(params.slice(0, 2)) + 1) + '}' + '  ' + params
									.slice(2)
								].join('\n')
							}
						}
					},
					data: []
				},
			
				textStyle: {
					fontSize: 12
				},
				tooltip: {
					show: false,
					trigger: 'item',
					showDelay: 0,
					transitionDuration: 0.2
				},
				toolbox: {
					show: true,
					left: 'left',
					top: 'top',
					feature: {
						dataView: {
							readOnly: false
						},
						restore: {},
						saveAsImage: {}
					}
				},
				backgroundColor: '#051B4A',
				geo: {
					map: 'china',
					label: {
						show: true,
						textStyle: {
							color: '#00a0c9',
							size: 8
						},
						color: '#ffffff',
						emphasis: {
							color: 'white',
							show: false
						}
					},
					roam: false, //是否允许缩放
					top: 30,
					left: 'left',
					right: '20',
					width: '90%',
					height: '80%',
					zoom: 1.2, //默认显示级别
					scaleLimit: {
						min: 0,
						max: 1
					}, //缩放级别
					itemStyle: {
						fontSize: 10,
						normal: {
							borderColor: '#5990FF',
							borderWidth: 1,
							areaColor: {
								type: 'radial',
								x: 0.5,
								y: 0.5,
								r: 0.8,
								colorStops: [{
									offset: 0,
									color: 'rgba(14, 101, 247, .1)' // 0% 处的颜色
								}, {
									offset: 1,
									color: 'rgba(125, 183, 252, .1)' // 100% 处的颜色
								}],
								globalCoord: false // 缺省为 false
							},
							shadowColor: 'rgba(255, 255, 255, 0)',
							shadowOffsetX: -2,
							shadowOffsetY: 2,
							shadowBlur: 10
						},
						emphasis: {
							areaColor: 'rgba(249,157,51, .2)',
							borderWidth: 0
						}
					},
					//是否显示南海诸岛
					/*regions: [{
					    name: "南海诸岛",
					    value: 0,
					    itemStyle: {
					        normal: {
					            opacity: 0,
					            label: {
					                show: false
					            }
					        }
					    }
					}],*/
					tooltip: {
						show: false
					}
				},
				series: []
			}
		},
		methods: {
			/** * renderjs内的点击事件，回调到父组件 * @param {Object} params */
			onViewClick(params) {
				this.$emit('click', params)
			}
		}
	}
</script>
<script module="echarts" lang="renderjs">
	import echarts from '@/components/echarts/echarts.min.js'
	export default {
		data() {
			return {
				chart: null,
				clickData: null, // echarts点击事件的值
				optionData: null,
				option: {
					title: [{
						show: true,
						text: '综合上机排行',
						subtext: '单位：台',
						subtextStyle: {
							color: '#ffffff',
							lineHeight: 10,
						},
						textStyle: {
							color: '#fff',
							fontSize: 12
						},
						right: 140,
						top: '182%'
					}],
					grid: {
						right: 10,
						top: '192%',
						left: '30%',
						height: '100%'
					},
					length: {
						height: '100%'
					},
					xAxis: {
						show: false
					},
					yAxis: {
						top: '120%',
						type: 'category',
						inverse: true,
						nameGap: 10,
						axisLine: {
							show: false,
							lineStyle: {
								color: '#ddd'
							}
						},
						axisTick: {
							show: false,
							lineStyle: {
								color: '#ddd'
							}
						},
						axisLabel: {
							interval: 0,
							margin: 85,
							textStyle: {
								color: '#fff',
								align: 'left',
								fontSize: 12
							},
							rich: {
								a: {
									color: '#fff',
									backgroundColor: '#f0515e',
									width: 12,
									height: 12,
									align: 'center',
									borderRadius: 2
								},
								b: {
									color: '#fff',
									backgroundColor: '#24a5cd',
									width: 12,
									height: 12,
									align: 'center',
									borderRadius: 1
								}
							},
							formatter: function(params) {
								if (parseInt(params.slice(0, 2)) < 3) {
									return [
										'{a|' + (parseInt(params.slice(0, 2)) + 1) + '}' + '  ' + params
										.slice(2)
									].join('\n')
								} else {
									return [
										'{b|' + (parseInt(params.slice(0, 2)) + 1) + '}' + '  ' + params
										.slice(2)
									].join('\n')
								}
							}
						},
						data: []
					},
				
					textStyle: {
						fontSize: 12
					},
					tooltip: {
						show: false,
						trigger: 'item',
						showDelay: 0,
						transitionDuration: 0.2
					},
					toolbox: {
						show: true,
						left: 'left',
						top: 'top',
						feature: {
							dataView: {
								readOnly: false
							},
							restore: {},
							saveAsImage: {}
						}
					},
					backgroundColor: '#051B4A',
					geo: {
						map: 'china',
						label: {
							show: true,
							textStyle: {
								color: '#00a0c9',
								size: 8
							},
							color: '#ffffff',
							emphasis: {
								color: 'white',
								show: false
							}
						},
						roam: false, //是否允许缩放
						top: 30,
						left: 'left',
						right: '20',
						width: '90%',
						height: '80%',
						zoom: 1.2, //默认显示级别
						scaleLimit: {
							min: 0,
							max: 1
						}, //缩放级别
						itemStyle: {
							fontSize: 10,
							normal: {
								borderColor: '#5990FF',
								borderWidth: 1,
								areaColor: {
									type: 'radial',
									x: 0.5,
									y: 0.5,
									r: 0.8,
									colorStops: [{
										offset: 0,
										color: 'rgba(14, 101, 247, .1)' // 0% 处的颜色
									}, {
										offset: 1,
										color: 'rgba(125, 183, 252, .1)' // 100% 处的颜色
									}],
									globalCoord: false // 缺省为 false
								},
								shadowColor: 'rgba(255, 255, 255, 0)',
								shadowOffsetX: -2,
								shadowOffsetY: 2,
								shadowBlur: 10
							},
							emphasis: {
								areaColor: 'rgba(249,157,51, .2)',
								borderWidth: 0
							}
						},
						//是否显示南海诸岛
						/*regions: [{
						    name: "南海诸岛",
						    value: 0,
						    itemStyle: {
						        normal: {
						            opacity: 0,
						            label: {
						                show: false
						            }
						        }
						    }
						}],*/
						tooltip: {
							show: false
						}
					},
					series: []
				},
			}
		},
		mounted() {
			this.init();
		},
		methods: {
			/** * 初始化echarts */
			init() {
				// 根据id初始化图表
				this.chart = echarts.init(document.getElementById(this.option.id));
				let jsonData = require('../../util/map/china.json')
				echarts.registerMap('china', jsonData)
				// let worldData = require('../../util/map/world.json')
				// echarts.registerMap('world', worldData)
				var namedata = [{
						name: '张'
					}, {
						name: '刘'
					}, {
						name: '李'
					}, {
						name: '邓'
					}, {
						name: '熊'
					}, {
						name: '田'
					}, {
						name: '周'
					}, {
						name: '赵'
					}, {
						name: '钱'
					}, {
						name: '孙'
					},
					{
						name: '吴'
					}, {
						name: '郑'
					}, {
						name: '王'
					}, {
						name: '冯'
					}, {
						name: '陈'
					}, {
						name: '杨'
					}, {
						name: '朱'
					}, {
						name: '秦'
					}, {
						name: '许'
					}, {
						name: '徐'
					},
					{
						name: '何'
					}, {
						name: '曹'
					}, {
						name: '陶'
					}, {
						name: '邹'
					}, {
						name: '苏'
					}, {
						name: '范'
					}, {
						name: '彭'
					}, {
						name: '鲁'
					}, {
						name: '马'
					}, {
						name: '方'
					},
					{
						name: '唐'
					}, {
						name: '顾'
					}
				];
				this.namedata = namedata
				var geoCoordMap = require('../../util/map/china.json')
				console.log(geoCoordMap)
				this.geoCoordMap = geoCoordMap.features
				var chinaDatas = [{
						name: '北京',
						value: 36
					},
					{
						name: '福建',
						value: 65
					},
					{
						name: '广东',
						value: 53
					},
					{
						name: '上海',
						value: 48
					},
				
					{
						name: '河北',
						value: 95
					},
					{
						name: '天津',
						value: 62
					},
					{
						name: '山西',
						value: 12
					},
					{
						name: '陕西',
						value: 2
					},
					{
						name: '甘肃',
						value: 4
					},
					{
						name: '宁夏',
						value: 5
					},
					{
						name: '青海',
						value: 3
					},
					{
						name: '新疆',
						value: 3
					},
					{
						name: '西藏',
						value: 5
					},
					{
						name: '四川',
						value: 22
					},
					{
						name: '重庆',
						value: 12
					},
					{
						name: '山东',
						value: 9
					},
					{
						name: '河南',
						value: 9
					},
					{
						name: '江苏',
						value: 24
					},
					{
						name: '安徽',
						value: 15
					},
					{
						name: '湖北',
						value: 6
					},
					{
						name: '浙江',
						value: 15
					},
					{
						name: '内蒙古',
						value: 3
					},
					{
						name: '江西',
						value: 34
					},
					{
						name: '湖南',
						value: 12
					},
					{
						name: '贵州',
						value: 8
					},
					{
						name: '广西',
						value: 16
					},
					{
						name: '海南',
						value: 37
					},
					{
						name: '辽宁',
						value: 2
					},
					{
						name: '吉林',
						value: 4
					},
					{
						name: '云南',
						value: 34
					},
					{
						name: '黑龙江',
						value: 5
					},
					{
						name: '台湾',
						value: 43
					}
				];
				this.chinaDatas = chinaDatas
				var yData = [];
				var barData = chinaDatas;
				barData = barData.sort((a, b) => {
					return b.value - a.value;
				});
				for (var j = 0; j < barData.length; j++) {
					if (j < 10) {
						yData.push('0' + j + barData[j].name);
					} else {
						yData.push(j + barData[j].name);
					}
				}
				this.option.series.push({
						type: 'effectScatter',
						coordinateSystem: 'geo',
						z: 1,
						data: [{
							name: '',
							username: 'this.getName(runidx)',
							telphone: 'this.getTel()',
							address: 'this.getAddress(dataidx, typeidx)',
							value: [' 87.92361', '43.5883', '73', '5', '0']
						}],
						symbolSize: 12,
						label: {
							normal: {
								show: true,
								formatter: function(params) {
									return '{fline|客户：' + params.data.username + '  ' + params
										.data
										.telphone + '}\n{tline|' + params.data.address + '}';
								},
								position: 'top',
								backgroundColor: 'rgba(254,174,33,.8)',
								padding: [0, 0],
								borderRadius: 3,
								lineHeight: 26,
								color: '#f7fafb',
								rich: {
									fline: {
										padding: [0, 10, 10, 10],
										color: '#ffffff'
									},
									tline: {
										padding: [10, 10, 0, 10],
										color: '#ffffff'
									}
								}
							},
							emphasis: {
								show: true
							}
						},
						itemStyle: {
							color: '#feae21',
						}
					}, {
						type: 'effectScatter',
						coordinateSystem: 'geo',
						z: 1,
						data: [{
							name: '',
							username: 'this.getName(runidx)',
							telphone: 'this.getTel()',
							address: 'this.getAddress(dataidx, typeidx)',
							value: [' 87.92361', '43.5883', '73', '5', '0']
						}],
						symbolSize: 12,
						label: {
							normal: {
								show: true,
								formatter: function(params) {
									return '{fline|客户：' + params.data.username + '  ' + params
										.data
										.telphone + '}\n{tline|' + params.data.address + '}';
								},
								position: 'top',
								backgroundColor: 'rgba(233,63,66,.9)',
								padding: [0, 0],
								borderRadius: 3,
								lineHeight: 26,
								color: '#ffffff',
								rich: {
									fline: {
										padding: [0, 10, 10, 10],
										color: '#ffffff'
									},
									tline: {
										padding: [10, 10, 0, 10],
										color: '#ffffff'
									}
								}
							},
							emphasis: {
								show: true
							}
						},
						itemStyle: {
							color: '#e93f42',
						}
					}, {
						type: 'effectScatter',
						coordinateSystem: 'geo',
						z: 1,
						data: [{
							name: '',
							username: 'this.getName(runidx)',
							telphone: 'this.getTel()',
							address: 'this.getAddress(dataidx, typeidx)',
							value: [' 87.92361', '43.5883', '73', '5', '0']
						}],
						symbolSize: 12,
						label: {
							normal: {
								show: true,
								formatter: function(params) {
									return '{fline|客户：' + params.data.username + '  ' + params
										.data
										.telphone + '}\n{tline|' + params.data.address + '}';
								},
								position: 'top',
								backgroundColor: 'rgba(8,186,236,.9)',
								padding: [0, 0],
								borderRadius: 3,
								lineHeight: 26,
								color: '#ffffff',
								rich: {
									fline: {
										padding: [0, 10, 10, 10],
										color: '#ffffff'
									},
									tline: {
										padding: [10, 10, 0, 10],
										color: '#ffffff'
									}
								}
							},
							emphasis: {
								show: true
							}
						},
						itemStyle: {
							color: '#08baec',
						}
					},
					//地图
					{
						type: 'map',
						mapType: 'china',
						geoIndex: 0,
						z: 0,
						data: this.convertData(chinaDatas, 1)
					}, {
						name: 'barSer',
						type: 'bar',
						roam: false,
						visualMap: false,
						zlevel: 2,
						barMaxWidth: 16,
						barGap: 0,
						itemStyle: {
							normal: {
								color: function(params) {
									var colorList = [{
											colorStops: [{
												offset: 0,
												color: '#f0515e'
											}, {
												offset: 1,
												color: '#ef8554'
											}]
										},
										{
											colorStops: [{
												offset: 0,
												color: '#3c38e4'
											}, {
												offset: 1,
												color: '#24a5cd'
											}]
										}
									];
									if (params.dataIndex < 3) {
										return colorList[0]
									} else {
										return colorList[1]
									}
								},
								barBorderRadius: [0, 15, 15, 0]
							}
						},
						label: {
							normal: {
								show: true,
								textBorderColor: '#333',
								textBorderWidth: 2
							}
						},
						data: barData.sort((a, b) => {
							return b.value - a.value;
						})
					})
				// this.timer = setInterval(() => {
				// 	var runidx = Math.floor(Math.random() * 3);
				// 	var typeidx = Math.floor(Math.random() * 6);
				// 	var dataidx = Math.floor(Math.random() * 32);
				// 	var ranval = Math.floor(Math.random() * 10);
				// 	chinaDatas[dataidx].value = chinaDatas[dataidx].value + ranval;
				// 	var valarr = this.geoCoordMap[dataidx].properties.center;
				// 	valarr.push(ranval);
				// 	this.option.series[runidx].data = [{
				// 		name: '',
				// 		username: this.getName(runidx),
				// 		telphone: this.getTel(),
				// 		address: this.getAddress(dataidx, typeidx),
				// 		value: valarr
				// 	}];
				// 	this.option.series[4].data = this.option.series[4].data.sort(function(a, b) {
				// 		return b.value - a.value;
				// 	});
				// 	// console.log(this.option1)
				// 	// let _this = this
				// 	// _this.$refs.updataEcharts.init(this.option);
				// }, 10000);
				this.update(this.option);
				console.log(this.chart, 'this.chart');
				// echarts的点击事件
				this.chart.on('click', params => {
					// 把点击事件的数据缓存下来
					this.clickData = params;
				})
			},
			convertData(data, type) {
				/*type:1 地图参数；type:2数据参数*/
				var res = [];
				for (var i = 0; i < data.length; i++) {
					var geoCoord = this.geoCoordMap[i].properties.name;
					if (geoCoord) {
						if (type == 2) {
							res.push({
								name: data[i].name,
								value: geoCoord.concat(data[i].value),
								username: data[i].username,
								telphone: data[i].telphone,
								address: data[i].address
							});
						} else {
							res.push({
								name: data[i].name,
								value: geoCoord.concat(data[i].value)
							});
						}
					}
				}
				//console.log(res);
				return res;
			},
			getTel() {
				var n = 2,
					telstr = '1';
				while (n < 12) {
					if (n < 3) {
						while (1) {
							var nums = Math.floor(Math.random() * 10);
							if (nums !== 0 && nums !== 1 && nums !== 2 && nums !== 3 && nums !== 4 && nums !== 6) {
								telstr += nums;
								break;
							}
						}
			
					} else if (n > 3 && n < 8) {
						telstr += '*';
					} else {
						telstr += Math.floor(Math.random() * 10);
					}
					n++;
				}
				return telstr;
			},
			
			getName(type) {
				var name = '';
				var roundnum = Math.floor(Math.random() * 32);
				switch (type) {
					case 1:
						name = this.namedata[roundnum].name + '先生';
						break;
					case 2:
						name = this.namedata[roundnum].name + '女士';
						break;
					default:
						name = this.namedata[roundnum].name + '先生';
						break;
				}
				return name;
			},
			
			getAddress(num, type) {
				var addstr = '';
				switch (type) {
					case 1:
						addstr = '在' + this.chinaDatas[num].name + '-火虎智算云系统上线了一台小盒子';
						break;
					case 2:
						addstr = '在' + this.chinaDatas[num].name + '-火虎智算云系统上线了一台X86';
						break;
					case 3:
						addstr = '在' + this.chinaDatas[num].name + '-火虎智算云系统上线了一台V聚合';
						break;
					case 4:
						addstr = '在' + this.chinaDatas[num].name + '-火虎智算云系统下线了一台小盒子';
						break;
					case 5:
						addstr = '在' + this.chinaDatas[num].name + '-火虎智算云系统下线了一台X86';
						break;
					default:
						addstr = '在' + this.chinaDatas[num].name + '-火虎智算云系统下线了一台V聚合';
						break;
				}
				return addstr;
			},
			/** * 点击事件，可传递到外部 * @param {Object} event * @param {Object} instance */
			onClick(event, instance) {
				console.log(event, instance, this.clickData, 'event, instance');
				// console.log(event, instance,'event, instance');
				if (this.clickData) {
					// 把echarts点击事件相关的值传递到renderjs外

					instance.callMethod('onViewClick', {
						value: this.clickData.data,
						name: this.clickData.name,
						seriesName: this.clickData.seriesName
					})
					// 上次点击数据置空
					this.clickData = null
				}
			},
			/** * 监测数据更新 * @param {Object} option */
			update(option) {
				if (this.chart) {
					// 因App端，回调函数无法从renderjs外传递，故在此自定义设置相关回调函数
					if (option) {
						// tooltip
						// if (option.tooltip) {
						// 	// 判断是否设置tooltip的位置
						// 	if (option.tooltip.positionStatus) {
						// 		option.tooltip.position = this.tooltipPosition()
						// 	}
						// 	// 判断是否格式化tooltip
						// 	if (option.tooltip.formatterStatus) {
						// 		option.tooltip.formatter = this.tooltipFormatter(option.tooltip.formatterUnit, option
						// 			.tooltip.formatFloat2, option.tooltip.formatThousands)
						// 	}
						// }
					}
					// 设置新的option
					this.chart.setOption(option, true)
				}
			},
			/** * 设置tooltip的位置，防止超出画布 */
			tooltipPosition() {
				return (point, params, dom, rect, size) => {
					// 其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
					let x = point[0]
					let y = point[1]
					let viewWidth = size.viewSize[0]
					let viewHeight = size.viewSize[1]
					let boxWidth = size.contentSize[0]
					let boxHeight = size.contentSize[1]
					let posX = 0 // x坐标位置
					let posY = 0 // y坐标位置
					if (x >= boxWidth) { // 左边放的下
						posX = x - boxWidth - 1
					}
					if (y >= boxHeight) { // 上边放的下
						posY = y - boxHeight - 1
					}
					return [posX, posY]
				}
			},
			/** * tooltip格式化 * @param {Object} unit 数值后的单位 * @param {Object} formatFloat2 是否保留两位小数 * @param {Object} formatThousands 是否添加千分位 */
			tooltipFormatter(unit, formatFloat2, formatThousands) {
				return params => {
					let result = ''
					unit = unit ? unit : ''
					for (let i in params) {
						if (i == 0) {
							result += params[i].axisValueLabel
						}
						let value = '--'
						if (params[i].data !== null) {
							value = params[i].data
							// 保留两位小数
							if (formatFloat2) {
								value = this.formatFloat2(value)
							}
							// 添加千分位
							if (formatThousands) {
								value = this.formatThousands(value)
							}
						}
						// #ifdef H5
						result += '\n' + params[i].seriesName + '：' + value + ' ' + unit
						// #endif
						// #ifdef APP-PLUS
						result += '<br/>' + params[i].marker + params[i].seriesName + '：' + value + ' ' + unit
						// #endif
					}
					return result
				}
			},
			/** * 保留两位小数 * @param {Object} value */
			formatFloat2(value) {
				let temp = Math.round(parseFloat(value) * 100) / 100
				let xsd = temp.toString().split('.')
				if (xsd.length === 1) {
					temp = (isNaN(temp) ? '0' : temp.toString()) + '.00'
					return temp
				}
				if (xsd.length > 1) {
					if (xsd[1].length < 2) {
						temp = temp.toString() + '0'
					}
					return temp
				}
			},
			/** * 添加千分位 * @param {Object} value */
			formatThousands(value) {
				if (value === undefined || value === null) {
					value = ''
				}
				if (!isNaN(value)) {
					value = value + ''
				}
				let re = /\d{1,3}(?=(\d{3})+$)/g
				let n1 = value.replace(/^(\d+)((\.\d+)?)$/, function(s, s1, s2) {
					return s1.replace(re, '$&,') + s2
				})
				return n1
			}
		}
	}
</script>
<style lang="scss" scoped>
	.echarts {
		width: 100%;
		height: 100%;
	}
</style>